package lc;
import org.junit.*;
public class Ex43 {
    class Solution {
        public String multiply(String num1, String num2) {
            int m = num1.length(), n = num2.length();
            if (m == 0 || n == 0 || num2.charAt(0) == '0' || 
            num1.charAt(0) == '0') return "0";
            int[] a = parseToArray(num1), b = parseToArray(num2);
            int[] nums = new int[m + n];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    nums[i + j] += a[i] * b[j];
                }
            }
            int len = m + n;
            StringBuilder sb = new StringBuilder();
            int flag = 0;
            for (int i = len - 2; i >= 0; i--) {
                nums[i] += flag;
                flag = nums[i] / 10;
                nums[i] %= 10;
                sb.insert(0, nums[i]);
            }
            if (flag > 0) {
                sb.insert(0, flag);
            }      
            return sb.toString();
        }
    
        public int[] parseToArray(String s) {
            int[] nums = new int[s.length()];
            int idx = 0;
            for (char c: s.toCharArray()) {
                nums[idx++] = c - '0';
            }
            return nums;
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        System.out.println(s.multiply("123","456"));        
    }
}
